package com.zmzncs.lmtc.common.interactive.miwang;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Objects;

@Slf4j
public class MiWangAESUtil {

    private static final int SECRETKEY_LENGTH = 128;
    private static final String KEY_ALGORITHM = "AES";
    private static final String INSTANCE_ALGORITHM = "SHA1PRNG";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默认的加密算法
    private static final String KEY = "DRE@5F98H!^HAFF%DFS#R399&DF8543^UR"; // key

    public static void main(String[] args) {
        System.out.println(decrypt("fvxdb8qK74zExiIkqqqji+ZwZhSneBKeundaSEa6cL8Bek3l3e8ThbThGvNSPlrwzTrETbb7H5dLzWBv9j3x8syvYqNL6T3dnpXQb4DCIY6LHpMVaJE8y9vNasf1kibncpaVIEU8y4/A0SeV68fyHNRTrwqWiI6jXZDdZ2YBZOwr/h4QlEX9zVqU0v6GWKeSG110GeEXcOXovRTog6vbszzZkWhZT8GRgOBYRq3Y22lVuLno59M7I1HysS/TZVBz3KIAUSYSNfRtcG8KW37Bn+pu1N/NW46Ytc9roxGd0HwB3MqoMR9jX3engoiURgZxQtpZcGxcZIbjb8LstDeYAfq/Q0Ex2n2q87ObZa1w9ZHPvxrkctFdgDQY8f7Il5MdLY2qSwDZeujBXWrJDFFrCSQdIowAN/ZABTo3tAnBOCY+ls4nbFymVaG178CM3ALFx04vqLjysNUkro3QaAWfPj/wyDkeo83w2vGFxmoIH2MzoeVXCc/MW8rpkZYKxVeq7v6IUdWAihCpEYeE9PQRMBIcFuIQICCHRIga0rnUOupolc8Y5UFozLCj4vk+GivqRnl12g/S/kmuOLweRB/pS0c8oEIpvGFnzsW1+GsU+Swe4un3Zr9hEH03A1XUb/Pw+0SkpTr1oiz0l9SCBOAS40QVyQQEnWddIhMyylP0JJIzO6bW5Hmf5dEr20ym2dhec8oQWQ8QL5VvQnU8t86utA5yBSH+HSyHHkqeVAhaEQDl3J1YqLlX9o9D+5RS05vc1xsxwElGbhv1Kcau6v/gbi7UQm4Gko61trHT3hUVZAcb/vIGIGDxSWt0FD/noZTDXUvhjrndTtfuudtzivzvcWd03VLiOOFGOMCEGlvUwBE=",KEY));
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content) {
        return encrypt(content, KEY);
    }


    /**
     * AES 加密操作
     *
     * @param content 密文
     * @return 返回Base64转码后的加密数据
     */
    public static String decrypt(String content) {
        return decrypt(content, KEY);
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param key     加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器

            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);

            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化为加密模式的密码器

            byte[] result = cipher.doFinal(byteContent);// 加密

            return Base64.encodeBase64String(result);
        } catch (Exception ex) {
            log.info("加密失败", ex);
        }

        return null;
    }

    public static String decryptByKey(String content){
       return decrypt(content, KEY );
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(String content, String key) {
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            //执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(content));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            log.info("解密失败", ex);
        }

        return null;
    }

    /**
     * 获得秘密密钥
     *
     * @param secretKey
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static SecretKey getSecretKey(String secretKey) throws NoSuchAlgorithmException {
        // 防止linux下随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance(INSTANCE_ALGORITHM);
        secureRandom.setSeed(secretKey.getBytes());

        // 生成一个KeyGenerator对象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            log.info("生成密钥初始化失败", ex);
        }
        Objects.requireNonNull(kg).init(SECRETKEY_LENGTH, secureRandom);

        // 生成密钥
        return kg.generateKey();
    }

}
